package com.yy.jhl.ui.manager.presenter;

import com.google.gson.Gson;
import com.yy.common.commonutils.StringUtil;
import com.yy.jhl.api.Api;
import com.yy.jhl.api.RxSubscriber;
import com.yy.jhl.bean.InvitePackageInfo;
import com.yy.jhl.bean.InviteUploadInfo;
import com.yy.jhl.ui.manager.contract.InviteUploadContract;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Observable;

/**
 * Created by libingn on 2017/12/18.
 */

public class InviteUploadPresenter extends InviteUploadContract.Presenter {
    @Override
    public void getHistoryInfo(String pack_num) {
        Observable observable;
        if (StringUtil.isEmpty(pack_num)){
            observable = Api.getDefault().getUploadHistory();
        }else {
            observable = Api.getDefault().getUploadHistory(pack_num);
        }
        mRxManage.addSubscription(observable, new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                InviteUploadInfo projectInfo = new Gson().fromJson(result,InviteUploadInfo.class);
                mView.getHistoryInfoSuccess(projectInfo);
            }

            @Override
            protected void _onError(String message) {
                mView.getHistoryInfoFail();
            }
        });
    }

    @Override
    public void uploadInfo(String package_id, String batch_id, final String remark, String image, String lng, String lat, String address) {
        RequestBody requestBody = new FormBody.Builder()
                .add("package_id", package_id)
                .add("batch_id", batch_id)
                .add("remark", remark)
                .add("image", image)
                .add("lng", lng)
                .add("lat", lat)
                .add("address", address)
                .build();
        mRxManage.addSubscription(Api.getDefault().uploadInfo(requestBody), new RxSubscriber<ResponseBody>(mContext,false) {
            @Override
            protected void _onNext(String result) {
                JSONObject resultObject = null;
                try {
                    resultObject = new JSONObject(result);
                    String package_completed = resultObject.optString("package_completed");
                    String package_total = resultObject.optString("package_total");
                    mView.uploadInfoSuccess(package_completed,package_total);
                } catch (JSONException e) {
                    e.printStackTrace();
//                    mView.uploadInfoSuccess("0");
                }
            }

            @Override
            protected void _onError(String message) {
                mView.uploadInfoFail();
            }
        });
    }
}
